import {
  BASE_API
} from "../../../utils/config";
import {
  updateUserInfo
} from "../../../api/miniProgramController";
import {
  updateNickNameAvatar
} from "../../../api/custBaseController";
import {
  getCustBaseByUserLoginState
} from "../../../api/custBaseController";
import {
  getTradeOrderCountByCustId
} from "../../../api/tradeOrderController";
import {
  mpId
} from "../../../utils/config";
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: BASE_API,
    balance: '0.00', //余额
    userInfo: '', //用户信息
    popupLoginVisible: false,
    tempNickName: '',
    tempAvatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    defaultAvatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    dfkCount: 0,
    djdCount: 0,
    pszCount: 0,
    ywcCount: 0,
    isAuthor: false //用户授权获取头像昵称
  },
  attached() {
    let userInfo = wx.getStorageSync('userInfo') || ''
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
    }
    this.getCustBaseByUserLoginState()
    this.getTradeOrderCountByCustId()
  },
  methods: {
    /**
     * 根据custId查询订单状态数量
     */
    async getTradeOrderCountByCustId() {
      let custId = wx.getStorageSync('custId')
      let resolve = await getTradeOrderCountByCustId({
        custId: custId
      })
      if (resolve.success) {
        let list = resolve.data
        for (let i = 0; i < list.length; i++) {
          if (list[i].status == 10) {
            this.setData({
              dfkCount: list[i].count
            })
          } else if (list[i].status == 20) {
            this.setData({
              djdCount: list[i].count
            })
          } else if (list[i].status == 30) {
            this.setData({
              pszCount: list[i].count
            })
          } else if (list[i].status == 40) {
            this.setData({
              ywcCount: list[i].count
            })
          }
        }

      }
    },
    /**
     * 登录,20240604由于更新了头像昵称获得的接口，本处做了相关的更新
     */
    getUserInfo() {
      let self = this
      wx.getUserProfile({
        desc: "获取你的昵称、头像、地区及性别",
        success: res => {
          self.updateUserInfo(res.userInfo)
        },
        fail: res => {
          //拒绝授权
          wx.showToast({
            title: '您拒绝了授权',
            icon: 'none'
          })
          return;
        }
      })
    },
    /**
     * 更新头像昵称-旧方法已被放弃
     */
    async updateUserInfo(res) {
      let self = this
      let resolve = await updateUserInfo({
        res: JSON.stringify(res),
        mpId: mpId
      })
      if (resolve.success) {
        self.getCustBaseByUserLoginState()
      }
    },
 
  /**
   * 输入框
   */
    onInput(e){
    console.log(e)
    let  nickName  = e.detail.value
    console.log("==当前昵称:"+nickName)
      this.setData({
        tempNickName : nickName
      })
      
    },

    onChooseAvatar(e){
      let that = this
       return new Promise((resolve, reject) => {
         wx.uploadFile({
           url: that.data.baseUrl + '/uploadAvatar',
           name: 'avatarUrl',
           filePath: e.detail.avatarUrl,
           header: {
             'content-type': ' multipart/form-data',
           },
           success: res => {
             console.log("服务器保存头像的位置:"+res.data)
             this.setData({
               tempAvatarUrl:res.data,
             })
   
           },  
           fail: res => {
             wx.showToast({
               title: '上传失败',
               icon: 'none',
               duration: 2000,
             })
           }
         })
       })
      },
    /**
     * 根据userLoginState获取当前客户
     */
    async getCustBaseByUserLoginState() {
      console.log("==个人中心页-登录执行==getCustBaseByUserLoginState：")
      let resolve = await getCustBaseByUserLoginState()
      if (resolve.success) {
          let userInfo = {
            "nickName": resolve.data.nickname,
            "realName": resolve.data.name,
            "gender": resolve.data.sex,
            "language": resolve.data.language,
            "city": resolve.data.city,
            "province": resolve.data.province,
            "country": resolve.data.country,
            "avatarUrl": resolve.data.headImgUrl,
            "vipType": resolve.data.vipType,
            "vipRank": resolve.data.vipRank,
            "id": resolve.data.id,
            "cloudPoint": resolve.data.cloudPoint,
            "cloudTicket": resolve.data.cloudTicket,
            "commission": resolve.data.commission,
            "typeName": resolve.data.typeName
          }
          wx.setStorageSync('userInfo', userInfo)
          wx.setStorageSync('custId', resolve.data.id)
          wx.setStorageSync('userBase', resolve.data)
          this.setData({
            userInfo: userInfo
          })
        }
       
      },
    btnShowtip(e){ 
      var msg = e.currentTarget.dataset.msg; 
      wx.showToast({ 
        title: msg, 
        icon: 'none', 
        image:'/static/images/service.png', 
        duration: 3000 
      })
    },
     
    showLogin(e){
      this.setData({
        popupLoginVisible:true,
      })
    },

    setLogin(e){
      if (this.data.tempAvatarUrl == this.data.defaultAvatarUrl) {
        wx.showToast({
          title: '请更新头像',
          icon: 'none'
        })
        return
      }
      if (this.data.tempNickName == '微信用户' || this.data.tempNickName == '') {
        wx.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return
      }
      this.setData({
        popupLoginVisible:false,
      })
      this.updateUserInfo({
        nickName: this.data.tempNickName,
        avatarUrl: this.data.tempAvatarUrl,
      })
    },

    setAuthor(e){
      var isApproved = e.currentTarget.dataset.approved === 'true';
      console.log(isApproved)
      e.target
        this.setData({
          isAuthor: isApproved,
          popupLoginVisible: isApproved,
        })
      },


      openFile(e) {
        let {
          name,
          title
        } = e.currentTarget.dataset
        // 加载状态
        wx.showLoading({
          title: '文件打开中',
          mask: true
        });
        wx.downloadFile({
          // 示例 url，并非真实存在
          url: `${BASE_API}/pdf/${name}`,
          filePath: `${wx.env.USER_DATA_PATH}/${title}`,
          success: function (res) {
            const filePath = res.filePath
            wx.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {
                console.log('打开文档成功')
              },
              fail: function () {
                console.log('打开文件失败，请稍后重试')
              }
            })
            wx.hideLoading();
          },
          fail: function () {
            wx.hideLoading();
            wx.showToast({
              title: '打开文件失败，请稍后重试',
              icon: 'none'
            })
          }
        })
      },

    },


})